<?php

namespace app\common\service\user;

use app\common\model\order\Order;
use app\common\model\order\OrderProduct;
use app\common\model\settings\Setting;
use app\common\enum\order\OrderAwardEnum;
use app\common\enum\order\OrderPayStatusEnum;
use app\common\enum\order\OrderStatusEnum;
use app\common\model\user\GradeProduct;
use app\common\model\user\User;
use app\job\model\user\User as JobUserModel;
/**
 * 用户等级服务类
 */
class GradeService
{
    //购物升级
    public static function updateByOrder($order_id)
    {
        $order = Order::find($order_id);
        if ($order->isEmpty()) {
            return true;
        }
        $pay_status = $order->pay_status['value'];
        $order_status = $order->order_status['value'];
        $app_id = $order->app_id;
        $trade_set = Setting::getItem("trade", $app_id);
        $award_timing = $trade_set['award_timing'];
        if ($pay_status != OrderPayStatusEnum::SUCCESS || ($order_status != OrderStatusEnum::COMPLETED && $order_status != OrderStatusEnum::NORMAL)) {
            return true;        //订单未支付或订单状态不是交易中或已完成跳过
        }
        if ($award_timing == OrderAwardEnum::AWARD_TIMING_CONFIRMED && $order_status != OrderStatusEnum::COMPLETED) {
            halt("here2");
            return true;    //如果是订单完成发放奖励，订单状态不是已完成跳过
        }
        $products = OrderProduct::where('order_id', $order_id)->column(['product_id']);
        if (empty($products)) {
            halt("here3");
            return true;
        }
        $user = User::detail($order->user_id);
        $weight = $user['grade']['weight'] ?? 0;
        $upgradeGrade = null;
        foreach ($products as $p_id) {
            $grade = GradeProduct::where('product_id', $p_id)->with(['grade'])->find();
            if ($grade && $grade['grade']['weight'] > $weight) {
                $upgradeGrade = $grade['grade'];
                $weight = $grade['grade']['weight'];
            }
        }
        if ($upgradeGrade) {
            self::doSetUserGrade($user, $upgradeGrade);
        }
    }

    public static function doSetUserGrade($user, $grade)
    {
        // 修改会员的等级
        (new JobUserModel())->upgradeGrade($user, $grade);
        // 赠送积分
        if ($grade['give_points'] > 0) {
            $user->setIncPoints($grade['give_points'], '用户升级赠送积分', false);
        }
    }
}